<script setup>
import {onBeforeMount, ref} from "vue";
import router from "../../../router";
import {ElMessage} from "element-plus";
import {getResponseData} from "../../../util";
import {listApi} from "../../../api/role.js";
import {listMyRolesApi, updateMyRolesApi} from "../../../api/emp.js";
import MyNav from "../../../components/MyNav.vue";

// 获取当前员工主键和员工姓名
let empId = sessionStorage.getItem('empId');
let empName = sessionStorage.getItem('empName');

/* ==================== 查询员工角色 ==================== */
// 当前员工拥有的全部角色列表 + 组件ElTransfer需要的key数组
let myRoles = ref([]);
let valueKeys = ref([]);

async function listMyRoles() {
  let myRolesData = getResponseData(await listMyRolesApi(empId));
  if (myRolesData) {
    for (let i in myRolesData) {
      // 优化数组结构：该结构是组件ElTransfer需要的
      myRoles.value.push({
        'key': myRolesData[i]['id'],
        'label': myRolesData[i]['name']
      });
      // 组件ElTransfer需要的key数组
      valueKeys.value.push(myRolesData[i]['id']);
    }
  }
}

/* ==================== 查询全部角色 ==================== */
let allRoles = ref([]);

async function listAllRoles() {
  let allRolesData = getResponseData(await listApi());
  if (allRolesData) {
    for (let i in allRolesData) {
      // 优化数组结构：该结构是组件ElTransfer需要的
      allRoles.value.push({
        'key': allRolesData[i]['id'],
        'label': allRolesData[i]['name']
      });
    }
  }
}

/* ==================== 确认修改角色 ==================== */
async function updateMyRoles() {
  let res = await updateMyRolesApi({
    'empId': empId,
    'roleIds': valueKeys.value
  });
  let data = getResponseData(res);
  if (data) {
    ElMessage.success('角色列表更新成功！');
    await router.push('/Emp')
  }
}

/* ==================== 加载函数 ==================== */
onBeforeMount(() => {
  listMyRoles();
  listAllRoles();
});

</script>

<template>
  <div class="emp-roles-body">

    <my-nav :items="[
      {'icon': 'Avatar', 'label': '用户管理', 'url': '/Emp'},
      {'icon': 'User', 'label': '员工列表', 'url': '/Emp'},
      {'icon': 'UserFilled', 'label': '(' + empName + ') 的角色列表'},
    ]"/>

    <el-divider/>

    <el-transfer v-if="allRoles"
                 v-model="valueKeys"
                 :data="allRoles"
                 filterable
                 filter-placeholder="输入角色名称"
                 :titles="['全部可选角色', '当前已选角色']"
                 :props="{'key': 'key', 'label': 'label'}"
                 :button-texts="['移除', '添加']"/>

    <el-button class="update-roles-btn"
               type="primary"
               @click="updateMyRoles">确认修改
    </el-button>
  </div>
</template>

<style scoped lang="scss">
.emp-roles-body {
  text-align: center; // 内容居中

  .update-roles-btn {
    margin-top: 20px; // 上外边距
    width: 53%; // 宽度
  }
}

/* 修改EL穿梭框高度 */
:deep(.el-transfer-panel), :deep(.el-transfer-panel__body) {
  height: 500px; // 高度
}
</style>